import { defineStore } from 'pinia'
import type { TeachingResourceComment } from '../../types/Resource/TeachingResourceComment'

/**
 * 教学资源评论存储模块
 * 负责管理教学资源评论的全局状态
 */
export const useTeachingResourceCommentStore = defineStore('teachingResourceComment', {
    state: () => ({
        // 当前资源的评论列表
        comments: [] as TeachingResourceComment[],
        // 加载状态
        loading: false
    }),
    actions: {
        /**
         * 获取资源评论
         * @param resourceId - 资源ID
         */
        async fetchComments(resourceId: number) {
            this.loading = true
            try {
                // this.comments = await commentApi.getResourceComments(resourceId)
            } finally {
                this.loading = false
            }
        },

        /**
         * 添加评论
         * @param newComment - 新评论对象
         */
        async addComment(newComment: Omit<TeachingResourceComment, 'commentId' | 'commentTime'>) {
            this.loading = true
            try {
                // const created = await commentApi.addResourceComment(newComment)
                // this.comments.push(created)
            } finally {
                this.loading = false
            }
        },

        /**
         * 删除评论
         * @param commentId - 评论ID
         */
        async deleteComment(commentId: number) {
            this.loading = true
            try {
                // await commentApi.deleteResourceComment(commentId)
                // this.comments = this.comments.filter(c => c.commentId !== commentId)
            } finally {
                this.loading = false
            }
        }
    },
    getters: {
        /**
         * 获取按时间排序的评论
         */
        sortedComments(state): TeachingResourceComment[] {
            return [...state.comments].sort((a, b) =>
                new Date(b.commentTime!).getTime() - new Date(a.commentTime!).getTime()
            )
        }
    }
})
